use base64::encode;
use lazy_static::lazy_static;
use rand::distributions::Uniform;
use rand::Rng;
use ril::prelude::*;
use std::{
    fs::{remove_file, File},
    io::Read,
    time::{SystemTime, UNIX_EPOCH},
};

const IMG_WIDTH: u32 = 120;
const IMG_HEIGHT: u32 = 50;
const TEXT_START_X: u32 = 5;
const TEXT_START_Y: u32 = 5;
const TEXT_SIZE: f32 = 36.0;
const TEXT_CODE: &str = "ad2bf";
static IMG_BG: &Rgb = &Rgb::white();

fn init_temp_folder() -> String {
    let folder_name: &str = ".code_images";
    if !std::path::Path::new(folder_name).exists() {
        std::fs::create_dir(folder_name).expect("创建.code_images文件夹失败");
    }
    folder_name.to_owned()
}
lazy_static! {
    static ref TEMP_FOLDER: String = init_temp_folder();
}

fn gen_temp_file_name() -> String {
    let mut rng = rand::thread_rng();
    let current_time = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("duration_since错误")
        .as_secs();
    rng.sample(Uniform::new(current_time, current_time + 1000));
    let random_number: u32 = rng.gen();
    format!("{}/{}.png", *TEMP_FOLDER, random_number)
}

fn main() {
    let mut image = Image::new(IMG_WIDTH, IMG_HEIGHT, *IMG_BG);
    let font = Font::open(
        "test_font_inter.ttf",
        // Do note that the following is a specified optimal size
        // and not a fixed size for the font. It specifies what size
        // to optimize rasterizing for. You do not have to load the same
        // font multiple times for different sizes.
        20.0,
    )
    .expect("font");

    let text = TextSegment::new(&font, TEXT_CODE, Rgb::black())
        .with_position(TEXT_START_X, TEXT_START_Y)
        .with_size(TEXT_SIZE);

    image.draw(&text);
    let mut out = Vec::new();
    image
        .encode(ImageFormat::Png, &mut out)
        .expect("encode出错");
    // 将图片文件序列化为base64字符串
    let base64_str = encode(&out);

    println!("base64:{}", base64_str);
    // 网页端测试<img src=""/>
}
